import type {
  FC,
  WheelEventHandler,
  ForwardedRef,
  ReactNode,
  UIEvent
} from "react";
import "./style.css";
import LoadingPage from "../Loading";
import {
  useRef,
  useEffect,
  useImperativeHandle,
  forwardRef,
  memo
} from "react";
interface GetLoderProps {
  Refresh?: () => void;
  loding?: number;
}
const GetLoder: FC<GetLoderProps> = props => {
  // 根据 props 返回不同的加载器组件
  if (props.loding == 1) {
    return (
      <div className="h-6 w-full flex justify-center items-center ">
        <LoadingPage></LoadingPage>
      </div>
    );
  } else if (props.loding == 2) {
    return (
      <div
        className="w-full h-6 flex justify-center items-center text-cyan-300 text-[10px]"
        onClick={props.Refresh}
      >
        点击下拉刷新
      </div>
    );
  } else {
    return (
      <div
        className="w-full h-6 flex justify-center items-center text-gray-300 text-[10px]"
        onClick={props.Refresh}
      >
        暂无数据
      </div>
    );
  }
};
interface Props {
  children: ReactNode;
  loderpos?: "top" | "bottom";
  Refresh?: () => void;
  isloding?: number;
  onScroll?: (event: UIEvent<HTMLDivElement>) => void;
}
const SlideList = (
  props: Props,
  ref: ForwardedRef<{ slideBottom: () => void }>
) => {
  const elRef = useRef<HTMLDivElement>(null);
  const loder = useRef<boolean>();
  const lastScrollHeight = useRef<number>();
  useEffect(() => {
    if (props.loderpos == "top") {
      if (props.isloding === 2 && loder.current === true) {
        if (lastScrollHeight.current)
          elRef.current?.scrollTo(
            0,
            elRef.current?.scrollHeight - lastScrollHeight.current
          );
      }
      loder.current = props.isloding == 1 ? true : false;
      lastScrollHeight.current = elRef.current?.scrollHeight;
    }
  });
  const handleWheel: WheelEventHandler<HTMLDivElement> = e => {
    if (
      props.loderpos == "top" &&
      elRef.current?.scrollTop === 0 &&
      e.deltaY < 0
    ) {
      if (props.Refresh && props.isloding == 2) props.Refresh();
    }
  };
  useImperativeHandle(ref, () => {
    return {
      slideBottom: () => {
        if (elRef.current) elRef.current.scrollTop = elRef.current.scrollHeight;
      }
    };
  });
  return (
    <div
      className="overflow-y-scroll h-full w-full scrollbar select-none cursor-auto"
      ref={elRef}
      onWheel={handleWheel}
      onScroll={props.onScroll}
    >
      {props.loderpos == "top" ? (
        <GetLoder loding={props.isloding} Refresh={props.Refresh}></GetLoder>
      ) : (
        <></>
      )}
      {props.children}
      {props.loderpos == "bottom" ? (
        <GetLoder loding={props.isloding} Refresh={props.Refresh}></GetLoder>
      ) : (
        <></>
      )}
    </div>
  );
};

export default memo(forwardRef(SlideList));
